package com.jxust.vhremployee9092.security.handler;

import com.alibaba.fastjson.JSON;
import com.jxust.debate.feign.RedisService;
import com.jxust.debate.util.ResultEnum;
import com.jxust.debate.util.ResultVO;
import com.jxust.vhremployee9092.security.util.JavaWebToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 退出成功
 * @author tyeerth
 * @date 2020/12/18 - 15:32
 */
@Slf4j
@Component
public class AjaxLogoutSuccessHandler implements LogoutSuccessHandler {

    @Resource
    private RedisService redisService;

    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        String authHeader = httpServletRequest.getHeader("Authorization");
        final String authToken = authHeader.substring("Bearer ".length());
        Map<String, Object> stringObjectMap = JavaWebToken.parserJavaWebToken(authToken);
        String username = (String) stringObjectMap.get("userId");
        redisService.removeRedisKeyRemote(username);
        log.info("用户成功退出，token清除----");
        httpServletResponse.getWriter().write(JSON.toJSONString(ResultVO.result(ResultEnum.USER_LOGOUT_SUCCESS,true)));
    }
}